﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FindGreatestLinkedNode.Question;

namespace FindGreatestLinkedNode.Answer
{
    class Sofia : IFindNearestGreatestNodeInBinaryTree
    {
        static int result = 0;
        public int? FindNearestGreatestNode(Node root, int k)
        {
            if (root == null) return null;

            int parData = 0;
            Fun(parData, root, k);
            if (result > k) return result;
            else return null;
        }

        public void Fun(int parData, Node root, int k)
        {
            try
            {
                if (root.Data == k)
                {
                    if (root.RightChild != null && root.LeftChild != null)
                        result = Math.Max(parData, Math.Max(root.LeftChild.Data, root.RightChild.Data));
                    else if (root.RightChild != null)
                        result = Math.Max(parData, root.RightChild.Data);
                    else if (root.LeftChild != null)
                        result = Math.Max(parData, root.LeftChild.Data);
                    else result = parData;
                }

                parData = root.Data;
                Fun(parData, root.LeftChild, k);
                Fun(parData, root.RightChild, k);
            }
            catch
            {
            }

        }
    }
}
